package com.quick.common.utils.http;


import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


/**
 * 通用http发送方法
 *
 * @Author: Administrator
 * @Date: 2023/7/17
 */

@Slf4j
public class HttpUtils {
    private static final String CHARSET_PREFIX = "charset=";
    private static final String CONTENT_TYPE = "Content-Type";

    /**
     * get请求
     *
     * @param url 地址
     * @return json字符串
     */
    public static String sendGet(String url) {
        JSONObject jsonObject = new JSONObject();
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod(HttpMethod.GET.name());
            InputStream inputStream = con.getInputStream();
            byte[] buffer = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = inputStream.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, len, getCharset(con)));
            }
            inputStream.close();
            return sb.toString();
        } catch (Exception e) {
            log.error("{}.", e.getMessage(), e);
            jsonObject.put("error", e.getMessage());
        }
        return jsonObject.toString();
    }

    /**
     * 获取 HTTP 响应的字符集编码（charset）
     *
     * @param connection 连接对象
     */
    private static String getCharset(HttpURLConnection connection) {
        String contentTypeHeader = connection.getHeaderField(CONTENT_TYPE);

        if (contentTypeHeader != null && contentTypeHeader.contains(CHARSET_PREFIX)) {
            return contentTypeHeader.substring(contentTypeHeader.indexOf("=") + 1).trim().toUpperCase();
        } else {
            return StandardCharsets.UTF_8.name();
        }
    }
}